<template>
  <div id="filemanageDiv">
    <Breadcrumb content="文件档案" />
    <div class="bodyContent">
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-button type="text" icon="vxe-icon-square-left-fill" class-name="text-green" status="success" content="" @click="goBack"></vxe-button>
          <vxe-button type="text" icon="vxe-icon-square-right-fill" class-name="text-cyan" status="primary" content="" @click="saveList"></vxe-button>
          <vxe-button type="text" icon="vxe-icon-square-up-fill" class-name="text-red" content="" status="danger" @click="handleDelete"></vxe-button>
          <div class="current-path-inner" style="width: calc(100% - 120px);display: flex;align-items: center;">
            <span class="vxe-icon-folder text-orange" style="font-size: 1.6em"></span>
            <span style="cursor: pointer" class="path-item" v-for="(item, index) in urlPath" :key="item.id">
              <span class="text-bold" @click="clickUrlPath(item)">{{ item.name }}</span>
              <span class="vxe-icon-arrow-right padding-lr-xs" v-if="index !== urlPath.length - 1"></span>
            </span>
          </div>
        </template>
        <template #tools>
          <vxe-input v-model="searchForm.searchValue" clearable @clear="findFilesManagementList()" @keyup="keyupEnter">
            <template #prefix>
              <i class="vxe-icon-search my-red"></i>
            </template>
          </vxe-input>
          <vxe-button icon="vxe-icon-custom-column" class-name="text-black" content="" @click="changePreviewType"></vxe-button>
        </template>
      </vxe-toolbar>
      <Splitpanes>
        <Pane size="20">
          <div class="sampleType">
            <el-scrollbar style="height: 100%;">
              <vxe-table id="folderTbleId" resizable ref="folderTable" border="none" :show-header="false" height="auto" :menu-config="tableMenuTree" :tree-config="{ transform: true, line: false, rowField: 'id', parentField: 'pid', expandAll: true}" :expand-config="{ trigger: 'cell',expandAll: true}" :row-config="{ isCurrent: true, isHover: true }" :mouse-config="{ selected: true }" :edit-config="{ trigger: 'dblclick', mode: 'cell', showIcon: false }" :data="folderList" @toggle-tree-expand="toggleExpandChangeEvent" @cell-click="folderRowClick" @cell-menu="tableMenuCell" @menu-click="treeMenuClick" @cell-dblclick="folderDblclick">
                >
                <vxe-column field="name" title="文件夹" tree-node :edit-render="{ autofocus: '.vxe-input--inner', autoselect: true }">
                  <template #default="{ row }">
                    <span class="text-df padding-tb-sm cursor text-blod" style="cursor: pointer">
                      <template v-if="row.children && row.children.length">
                        <i class="tree-node-icon el-icon-folder-opened padding-lr-xs text-orange" :class="validateIsOpen(row) ? 'vxe-icon-folder-open' : 'vxe-icon-folder'"></i>
                      </template>
                      <template v-else>
                        <i class="tree-node-icon vxe-icon-folder padding-lr-xs text-orange"></i>
                      </template>
                      <span>{{ row.name }}</span>
                    </span>
                  </template>
                  <template #edit="{ row }">
                    <vxe-input v-model="row.name" type="text" @blur="editFolderRow(row)"></vxe-input>
                  </template>
                </vxe-column>
              </vxe-table>
            </el-scrollbar>
          </div>
        </Pane>
        <Pane size="80">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="floading" @click="findFilesManagementList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-copy" content="复制" @click="copyFileButton" :disabled="sltFoldTag&&sltFileTag"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-paste" content="粘贴" @click="pasteFile" :disabled="pasteTag"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建文件夹" @click="addFolderDialog"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-edit" content="重命名" @click="renameButton" :disabled="sltFoldTag&&sltFileTag"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-upload" content="上传" @click="upload"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-download" content="下载" @click="download" :disabled="sltFileTag"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-delete" content="删除" @click="handleDeleteFile" :disabled="sltFoldTag&&sltFileTag"></vxe-button>
            </template>
          </vxe-toolbar>
          <div v-show="previewType === 'list'" class="filesManagementTable" :style="{ height: isChildren ? 'calc(100% - 40px - 40px)' : 'calc(100%)' }">
            <vxe-table id="filesManagementTable" ref="filesManagementTable" v-loading="floading" border keep-source width="100%" height="auto" :data="filesManagementList" :menu-config="tableMenu" @cell-click="filesManagementRowClick" :row-config="{ isCurrent: true, isHover: true }" :mouse-config="{ selected: true }" :keyboard-config="{ isArrow: true, isTab: true, isEdit: true }" :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false }" resizable show-overflow @menu-click="menuClick" @cell-menu="cellMenuClick">
              <vxe-column field="name" title="名称" width="280px" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  <div class="flex justify-start">
                    <span class="vxe-icon-file-excel margin-right-xs" style="line-height: 22px" v-if="row.fileExten === 'xlsx'"></span>
                    <span class="vxe-icon-file-word margin-right-xs" style="line-height: 22px" v-if="row.fileExten === 'docx' || row.fileExten === 'doc'"></span>
                    <span class="vxe-icon-file-zip margin-right-xs" style="line-height: 22px" v-if="row.fileExten === 'zip'"></span>
                    <span class="vxe-icon-picture-fill margin-right-xs" style="line-height: 22px" v-if="row.fileExten === 'png'"></span>
                    <span class="vxe-icon-picture-fill margin-right-xs" style="line-height: 22px" v-if="row.fileExten === 'jpg'"></span>
                    <span class="vxe-icon-picture-fill margin-right-xs" style="line-height: 22px" v-if="row.fileExten === 'pptx'"></span>
                    <span class="vxe-icon-folder margin-right-xs" style="line-height: 22px" v-if="row.fileExten === 'explorer'"></span>
                    <span>{{ row.name }}</span>
                  </div>
                </template>
                <template #edit="{ row, rowIndex, column }">
                  <div class="flex justify-start">
                    <!-- <span class="vxe-icon-file-excel margin-right-xs" v-if="row.fileExten === 'xlsx'"></span>
                  <span class="vxe-icon-file-word margin-right-xs" v-if="row.fileExten === 'docx' || row.fileExten === 'doc'"></span>
                  <span class="vxe-icon-file-zip margin-right-xs" v-if="row.fileExten === 'zip'"></span>
                  <span class="vxe-icon-picture-fill margin-right-xs" v-if="row.fileExten === 'png'"></span>
                  <span class="vxe-icon-picture-fill margin-right-xs" v-if="row.fileExten === 'jpg'"></span>
                  <span class="vxe-icon-picture-fill margin-right-xs" v-if="row.fileExten === 'pptx'"></span>
                  <span class="vxe-icon-folder margin-right-xs" v-if="row.fileExten === 'explorer'"></span> -->
                    <vxe-input v-model="row.name" type="text" @keydown.native.enter="enterEvent(row, rowIndex, column)"></vxe-input>
                  </div>
                </template>
              </vxe-column>
              <vxe-column field="showtype" title="文件类型" width="100" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.showtype" type="text" @keydown.native.enter="enterEvent(row, rowIndex, column)"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="fileSize" title="大小" width="80" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.fileSize" type="text" @keydown.native.enter="enterEvent(row, rowIndex, column)"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="content" title="文件内容" width="120" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.content" type="text" @keydown.native.enter="enterEvent(row, rowIndex, column)"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="description" title="文件描述" min-width="120" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.description" type="text" @keydown.native.enter="enterEvent(row, rowIndex, column)"></vxe-input>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
          <div v-show="previewType === 'grid'" :style="{ height: 'calc(100%)' }">
            <vxe-table id="gridFileTable" resizable ref="gridFileTable" :border="'none'" width="100%" keep-source height="auto" :show-header="false" :menu-config="tableMenuGrid" @menu-click="menuClick" v-loading="floading">
              <vxe-column field="a">
                <template #default>
                  <div class="container" :style="{ height: 'calc(100%)' }">
                    <div v-for="(itm, index) in filesManagementList" :key="itm.id" class="list" :class="itm.isSelected ? 'selected' : ''" :body-style="{ padding: '2px' }" @click="itemCLick(itm)" @dblclick="folderDbClick(itm)" v-on:contextmenu="handleContextMenu(itm)">
                      <div style="display: flex; justify-content: center">
                        <span :style="{ backgroundImage: 'url(' + excelbg + ')' }" class="bg-image-wh" v-if="itm.fileExten === 'xlsx'"></span>
                        <span :style="{ backgroundImage: 'url(' + wordbg + ')' }" class="bg-image-wh" v-if="itm.fileExten === 'docx' || itm.fileExten === 'doc'"></span>
                        <span :style="{ backgroundImage: 'url(' + zipbg + ')' }" class="bg-image-wh" v-if="itm.fileExten === 'zip'"></span>
                        <span :style="{ backgroundImage: 'url(' + picturebg + ')' }" class="bg-image-wh" v-if="itm.fileExten === 'png'"></span>
                        <span :style="{ backgroundImage: 'url(' + picturebg + ')' }" class="bg-image-wh" v-if="itm.fileExten === 'jpg'"></span>
                        <span :style="{ backgroundImage: 'url(' + powerpointbg + ')' }" class="bg-image-wh" v-if="itm.fileExten === 'pptx'"></span>
                        <span :style="{ backgroundImage: 'url(' + folderbg + ')' }" class="bg-image-wh" v-if="itm.fileExten === 'explorer'"></span>
                        <span :style="{ backgroundImage: 'url(' + pdfbg + ')' }" class="bg-image-wh" v-if="itm.fileExten === 'pdf'"></span>
                      </div>
                      <div style="overflow: hidden; white-space: nowrap; font-size: 1em" class="title text-center">
                        <span v-if="!itm.isRename" class="text-cut" style="width: 60px; max-width: 60px">{{ itm.name ||
                        itm.title }}</span>
                        <vxe-input :ref="'rename' + index" v-if="itm.isRename" v-model="itm.name" align="center" className="text-center" style="width: 100%" type="text" @blur="renameBlurEvent(itm, index)" />
                      </div>
                    </div>
                  </div>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
      </Splitpanes>
    </div>

    <vxe-modal v-model="previewDocModal" width="80vw" show-footer destroy-on-close :mask="false">
      <template #title>
        <span>文档预览</span>
      </template>
      <template #default>
        <iframe style="width:75vw;height:80vh;" :src="filePath"></iframe>
      </template>
    </vxe-modal>

    <el-dialog :title="titleFolder()" :show-close="false" v-model="showFolderDialog" append-to-body :close-on-click-modal="false" width="500px">
      <el-form ref="wkFolderFormRef" :model="wkFolderForm" :rules="wkFolderFormRule" label-width="100px" class="form-input-m" inline-message>
        <el-form-item prop="pname" label="父级" v-if="pnameShow">
          <el-input type="text" v-model="wkFolderForm.pname" placeholder="请输入父类名称" disabled></el-input>
        </el-form-item>
        <el-form-item prop="code" label="编号">
          <el-input type="text" v-model="wkFolderForm.code" placeholder="请输入文件夹编号" clearable></el-input>
        </el-form-item>
        <el-form-item prop="name" label="名称">
          <el-input type="text" v-model="wkFolderForm.name" placeholder="请输入文件夹名称" clearable></el-input>
        </el-form-item>
        <el-form-item prop="fileFolder" label="绑定文件夹">
          <el-checkbox-group v-model="wkFolderForm.fileFolders">
            <el-checkbox v-for="(item, index) in fileFolderList" :label="item.code" :key="index">
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item prop="sx" label="排序" class="input-s">
          <el-input-number v-model="wkFolderForm.seq" :min="0" :max="100" label="请输入顺序号"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer flex right justify-end">
        <el-button type="primary" @click="saveFolder('wkFolderFormRef')">保存</el-button>
        <el-button @click="closeFolderDialog('wkFolderFormRef')">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 引入组件区==========
import { ref, reactive, getCurrentInstance, nextTick, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { AppStore } from '@/stores/store';
import { isEmpty } from 'lodash';
import VXETable from 'vxe-table';

import excelbg from '../../../assets/images/filemanager/excel.png';
import wordbg from '../../../assets/images/filemanager/word.png';
import powerpointbg from '../../../assets/images/filemanager/powerpoint.png';
import zipbg from '../../../assets/images/filemanager/zip.png';
import picturebg from '../../../assets/images/filemanager/picture.png';
import folderbg from '../../../assets/images/filemanager/folder.png';
import pdfbg from '../../../assets/images/filemanager/pdf.png';
import { IsEmpty } from '@/utils/common';

let { proxy }: any = getCurrentInstance();

VXETable.interceptor.add('event.showMenu', (params, event) => {
  if (params.$table.props.id == 'folderTbleId') {
    currentFolder = reactive({});
    (proxy.$refs.folderTable as any).setCurrentRow(null);
  }

  return true;
});

// 全局变量定义区 ==========
let store = AppStore();
let searchForm = {
  searchValue: ''
};
let wkFolderForm = reactive({
  id: null,
  pid: '',
  pname: '',
  orgId: '',
  code: '',
  name: '',
  fileFolders: [],
  grade: 0,
  seq: 0,
  remark: '',
  inputCode: ''
});

let wkFolderFormRule = {
  name: [
    {
      required: true,
      message: '请输入文件夹名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 40,
      message: '长度为2到40个字符',
      trigger: 'blur'
    }
  ]
};
const tableMenuTree = {
  className: 'my-menus',
  body: {
    options: [
      [
        { code: 'refresh', name: '刷新', prefixIcon: 'vxe-icon-refresh' },
        { code: 'insert', name: '新建', prefixIcon: 'vxe-icon-square-plus-fill' },
        { code: 'edit', name: '修改', prefixIcon: 'vxe-icon-edit' },
        { code: 'rename', name: '重命名', prefixIcon: 'vxe-icon-square' },
        { code: 'remove', name: '删除', prefixIcon: 'vxe-icon-delete color-red' }
      ]
    ]
  }
};

const tableMenu = {
  className: 'my-menus',
  body: {
    options: [
      [
        { code: 'refresh', name: '刷新', prefixIcon: 'vxe-icon-refresh' },
        { code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy' },
        { code: 'paste', name: '粘贴', prefixIcon: 'vxe-icon-paste' },
        { code: 'insert', name: '新建', prefixIcon: 'vxe-icon-square-plus-fill' },
        { code: 'remove', name: '删除', prefixIcon: 'vxe-icon-delete color-red' },
        { code: 'rename', name: '重命名', prefixIcon: 'vxe-icon-square' },
        { code: 'upload', name: '上传', prefixIcon: 'vxe-icon-cloud-download' },
        { code: 'download', name: '下载', prefixIcon: 'vxe-icon-cloud-upload' }
      ]
    ]
  }
};
const tableMenuGrid = {
  className: 'my-menus',
  body: {
    options: [
      [
        { code: 'refresh', name: '刷新', prefixIcon: 'vxe-icon-refresh' },
        { code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy' },
        { code: 'paste', name: '粘贴', prefixIcon: 'vxe-icon-paste' },
        { code: 'insert', name: '新建', prefixIcon: 'vxe-icon-square-plus-fill' },
        { code: 'remove', name: '删除', prefixIcon: 'vxe-icon-delete color-red' },
        { code: 'rename', name: '重命名', prefixIcon: 'vxe-icon-square' },
        { code: 'upload', name: '上传', prefixIcon: 'vxe-icon-cloud-download' },
        { code: 'download', name: '下载', prefixIcon: 'vxe-icon-cloud-upload' }
      ]
    ]
  }
};
let folderList: any = reactive([]);
let filesManagementList: any = reactive([]);
let fileFolderList: any = reactive([]);
let urlPath: any = reactive([]);
let tloading = ref(false); //加载状态
let floading = ref(false);
let showFolderDialog = ref(false);
let currentFolder: any = reactive({});
let pnameShow = ref(false); //父级分类显示
let previewType = ref('grid');
let filePath = ref('');
let isChildren = ref(false);
let previewDocModal = ref(false);
let copyFile: any = reactive({});
let pasteTag = ref(true); //中间质控品维护按钮标记
let sltFoldTag = ref(true);
let sltFileTag = ref(true);

let currentFilesManagement: any = reactive({});
// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  findFolderList(); // 获取最左侧 树形表格数据
  if (previewType.value === 'list') {
    (proxy.$refs.filesManagementTable as any).reloadData(filesManagementList);
  }
  if (previewType.value === 'grid') {
    (proxy.$refs.gridFileTable as any).reloadData([{ a: '2' }]);
  }
  getDictItemsList();
});
//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['eqFileFolder'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const planStatues = dictTreeTypeItems.data.find((item: any) => item.code === 'eqFileFolder');
  fileFolderList.push(...planStatues.detailDataList);
}
function findFolderList() {
  tloading.value = true;
  folderList.length = 0;
  const url = '/api/wk/wkFolder/findFolderList';
  proxy.$http
    //注意此处的数据条数
    .get(url)
    .then((res: any) => {
      folderList.push(...res.data);
      tloading.value = false;
      // 使用 nextTick 方法等待表格加载完成后再执行 setAllTreeExpand
      proxy.$nextTick(() => {
        (proxy.$refs.folderTable as any).setAllTreeExpand(true);
        if (isEmpty(currentFolder)) {
          folderRowClick({ row: folderList[0] });
        } else {
          if (isEmpty(folderList.find((item) => item.id == currentFolder.id))) {
            folderRowClick({ row: folderList[0] });
          } else {
            folderRowClick({ row: folderList.find((item) => item.id == currentFolder.id) });
          }
        }
      });
    })
    .catch((err: any) => {
      tloading.value = false;
    });
}

function findFilesManagementList() {
  floading.value = true;
  filesManagementList.length = 0;
  const url = '/api/wk/WkFile/findFolderAndFileList';
  let obj = { folderId: currentFolder.id };
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: obj })
    .then((res: any) => {
      filesManagementList.push(...res.data);
      currentFilesManagement = {} as any;
      sltFoldTag.value = true;
      sltFileTag.value = true;
      floading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
    });
}

function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findFilesManagementList();
  }
}

function goBack() {
  console.log('goBack');
}
function saveList() {
  console.log('saveList');
}
function handleDelete() {
  console.log('handleDelete');
}
function changePreviewType() {
  previewType.value = previewType.value == 'list' ? 'grid' : 'list';
  proxy.$nextTick(() => {
    findFilesManagementList();

    if (previewType.value == 'list') {
      (proxy.$refs.filesManagementTable as any).reloadData(filesManagementList);
    }
    if (previewType.value == 'grid') {
      (proxy.$refs.gridFileTable as any).reloadData([{ a: '2' }]);
    }
    proxy.$forceUpdate();
  });
}

function toggleExpandChangeEvent() {
  console.log('toggleExpandChangeEvent');
}

let sltFolderName = '';
let sltFileName = '';
function folderDblclick({ row }: any) {
  sltFolderName = row.name;
}

function folderRowClick({ row }: any) {
  sltFolderName = '';
  (proxy.$refs.folderTable as any).setCurrentRow(row);
  currentFolder = row;
  urlPath.length = 0;
  getParent(row, urlPath);
  findFilesManagementList();
}
function getParent(data, pathArr) {
  pathArr.unshift(data);
  if (data.pid) {
    const parent = folderList.find((row) => {
      return row.id === data.pid;
    });
    if (parent) {
      getParent(parent, pathArr);
    }
  }
}
function addFolderDialog() {
  const $table = proxy.$refs.folderTable as any;
  const record = $table.getCurrentRecord();
  if (isEmpty(record)) {
    wkFolderForm.pname = '';
    wkFolderForm.pid = '';
    pnameShow.value = false;
  } else {
    wkFolderForm.pname = record.name;
    wkFolderForm.pid = record.id;
    pnameShow.value = true;
  }

  wkFolderForm.orgId = store.userInfo.orgId;
  wkFolderForm.seq = folderList.length + 1;
  showFolderDialog.value = true;
}
function editFolderDialog() {
  const $table = proxy.$refs.folderTable as any;
  const record = $table.getCurrentRecord();
  if (isEmpty(record)) {
    VxeMessage('选择要修改的文件夹', VxeNotifyType.error);
  } else {
    wkFolderForm.id = record.id;
    wkFolderForm.pid = record.pid;
    wkFolderForm.orgId = record.orgId;
    wkFolderForm.code = record.code;
    wkFolderForm.name = record.name;
    wkFolderForm.grade = record.grade;
    wkFolderForm.seq = record.seq;
    wkFolderForm.remark = record.remark;
    wkFolderForm.inputCode = record.inputCode;
    wkFolderForm.fileFolders = IsEmpty(record.fileFolder) ? [] : record.fileFolder.split(',');
    if (!isEmpty(record.pid)) {
      wkFolderForm.pname = folderList.find((item) => item.id == record.pid).name;
      pnameShow.value = true;
    }
    showFolderDialog.value = true;
  }
}
function closeFolderDialog(formName: any) {
  const el: any = proxy.$refs[formName];
  //移除校验结果
  el.clearValidate();
  clearFolderForm();
  pnameShow.value = false;
  showFolderDialog.value = false;
}
function clearFolderForm() {
  wkFolderForm.id = null;
  wkFolderForm.pid = '';
  wkFolderForm.orgId = '';
  wkFolderForm.code = '';
  wkFolderForm.name = '';
  wkFolderForm.grade = 0;
  wkFolderForm.seq = 0;
  wkFolderForm.remark = '';
  wkFolderForm.inputCode = '';
}
function saveFolder(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    if (wkFolderForm.id === null) {
      const url = '/api/wk/wkFolder/addFolder';
      const folder = {
        pid: wkFolderForm.pid,
        orgId: wkFolderForm.orgId,
        code: wkFolderForm.code,
        name: wkFolderForm.name,
        grade: 0,
        seq: wkFolderForm.seq,
        inputCode: wkFolderForm.inputCode,
        remark: wkFolderForm.remark,
        fileFolder: wkFolderForm.fileFolders.length <= 0 ? null : wkFolderForm.fileFolders.join(',')
      };
      proxy.$http
        .post(url, folder)
        .then((res: any) => {
          VxeMessage('新增字段成功', VxeNotifyType.success);
          clearFolderForm();
          showFolderDialog.value = false;
          findFolderList();
        })
        .catch((err: any) => {
          VxeMessage('新增字段失败', VxeNotifyType.error);
        });
    } else {
      // 修改用户
      const url = '/api/wk/wkFolder/editFolder';
      const folder = {
        id: wkFolderForm.id,
        pid: wkFolderForm.pid,
        orgId: wkFolderForm.orgId,
        code: wkFolderForm.code,
        name: wkFolderForm.name,
        grade: 0,
        seq: wkFolderForm.seq,
        inputCode: wkFolderForm.inputCode,
        remark: wkFolderForm.remark,
        fileFolder: wkFolderForm.fileFolders.length <= 0 ? null : wkFolderForm.fileFolders.join(',')
      };
      proxy.$http
        .post(url, folder)
        .then((res: any) => {
          VxeMessage('修改字段成功', VxeNotifyType.success);
          clearFolderForm();
          showFolderDialog.value = false;
          findFolderList();
        })
        .catch((err: any) => {
          VxeMessage('修改字段失败', VxeNotifyType.error);
        });
    }
  });
}

function editFolderRow(row) {
  if (row.name === sltFolderName) {
    return;
  }
  // 修改用户
  const url = '/api/wk/wkFolder/editFolder';
  const folder = {
    id: row.id,
    pid: row.pid,
    orgId: row.orgId,
    code: row.code,
    name: row.name,
    grade: 0,
    seq: row.seq,
    inputCode: row.inputCode,
    remark: row.remark
  };
  proxy.$http
    .post(url, folder)
    .then((res: any) => {
      VxeMessage('修改成功', VxeNotifyType.success);
      findFolderList();
    })
    .catch((err: any) => {
      VxeMessage('修改失败', VxeNotifyType.error);
    });
}

function handleDeleteFolder() {
  const $table = proxy.$refs.folderTable as any;
  const record = $table.getCurrentRecord();
  if (isEmpty(record)) {
    VxeMessage('选择要删除的文件夹', VxeNotifyType.error);
  } else {
    proxy
      .$confirm('确定删除此文件夹？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        const url = '/api/wk/wkFolder/deleteFolder';
        proxy.$http.post(url, record).then((res: any) => {
          if (res.status.code === 1) {
            findFolderList();
            VxeMessage('删除成功', VxeNotifyType.success);
          } else {
            VxeMessage(res.status.msg, VxeNotifyType.error);
          }
        });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function tableMenuCell({ row, column }) {
  folderRowClick({ row });
}
function treeMenuClick({ menu, row, column }) {
  switch (menu.code) {
    case 'refresh': //刷新
      findFolderList();
      break;
    case 'insert':
      addFolderDialog();
      break;
    case 'remove': //删除
      handleDeleteFolder();
      break;
    case 'rename': //删除
      sltFolderName = row.name;
      (proxy.$refs.folderTable as any).setEditRow(currentFolder);
      break;
    case 'edit': //重命名
      editFolderDialog();
      break;
    default:
      break;
  }
}
function titleFolder() {
  if (wkFolderForm.id) {
    return `编辑文件夹`;
  } else if (!wkFolderForm.id) {
    return `新建文件夹`;
  }
}
function validateIsOpen(row) {
  return (proxy.$refs.folderTable as any).isTreeExpandByRow(row);
}

function itemCLick(row) {
  currentFilesManagement.isSelected = false;
  currentFilesManagement = row;
  if (currentFilesManagement.fileExten == 'explorer') {
    sltFoldTag.value = false;
    sltFileTag.value = true;
  } else {
    sltFoldTag.value = true;
    sltFileTag.value = false;
  }

  currentFilesManagement.isSelected = true;
}
function handleContextMenu(row) {
  currentFilesManagement.isSelected = false;
  currentFilesManagement = row;
  if (currentFilesManagement.fileExten == 'explorer') {
    sltFoldTag.value = false;
    sltFileTag.value = true;
  } else {
    sltFoldTag.value = true;
    sltFileTag.value = false;
  }
  currentFilesManagement.isSelected = true;
}

function folderDbClick(fdc) {
  if (fdc.fileExten === 'explorer') {
    folderRowClick({ row: folderList.find((item) => item.id == fdc.id) });
  } else {
    if (fdc.fileExten === 'pdf') {
      previewDocModal.value = true;
      const url = (window as any).apiUrl.VITE_SERVER_URL + '/api/wk/WkFile/viewWkFile';
      filePath.value = url + '?id=' + fdc.id;
    }
  }
}
function menuClick({ menu, row, column }) {
  if (isEmpty(currentFolder)) {
    VxeMessage('请选择文件夹', VxeNotifyType.error);
    return;
  }

  switch (menu.code) {
    case 'refresh': //刷新
      findFilesManagementList();
      break;
    case 'copy': //复制
      copyFileButton();
      break;
    case 'paste': //粘贴
      pasteFile();
      break;
    case 'insert': //新建文件夹
      addFolderDialog();
      break;
    case 'rename': //重命名
      renameButton();
      break;
    case 'upload': //上传
      upload();
      break;
    case 'download': //下载
      download();
      break;
    case 'remove': //删除
      handleDeleteFile();
      break;
    default:
      break;
  }
}
function cellMenuClick() {
  console.log('cellMenuClick');
}

function pasteFile() {
  if (isEmpty(copyFile)) {
    VxeMessage('请先选中行复制', VxeNotifyType.error);
  } else {
    const index = filesManagementList.findIndex((item) => item.name == copyFile.name);

    if (copyFile.fileExten == 'explorer') {
      if (index !== -1) {
        copyFile.name = `${copyFile.name} - 副本`;
      } else {
        copyFile.folderId = currentFolder.id;
      }
      copyFile.id = null;
      const url = '/api/wk/wkFolder/addFolder';
      const folder = {
        pid: copyFile.folderId,
        orgId: copyFile.orgId,
        code: copyFile.code,
        name: copyFile.name,
        grade: 0,
        seq: copyFile.seq,
        inputCode: copyFile.inputCode,
        remark: copyFile.remark
      };
      proxy.$http
        .post(url, folder)
        .then((res: any) => {
          VxeMessage('新增成功', VxeNotifyType.success);
          findFolderList();
        })
        .catch((err: any) => {
          VxeMessage('新增失败', VxeNotifyType.error);
        });
    } else {
      if (index !== -1) {
        // copyFile.name = `${copyFile.name} - 副本`;
        const dotIndex = copyFile.name.lastIndexOf('.');
        const filePrefix = dotIndex ? copyFile.name.substring(0, dotIndex) : copyFile.name;
        const fileSuffix = dotIndex ? copyFile.name.substring(dotIndex + 1) : '';
        copyFile.name = filePrefix + '- 副本.' + fileSuffix;
      } else {
        copyFile.folderId = currentFolder.id;
      }
      copyFile.id = null;
      const url = '/api/wk/WkFile/copyFile';

      proxy.$http
        .post(url, copyFile)
        .then((res: any) => {
          VxeMessage('新增成功', VxeNotifyType.success);
          findFilesManagementList();
        })
        .catch((err: any) => {
          VxeMessage('新增失败', VxeNotifyType.error);
        });
    }
  }
}
function upload() {
  const $grid = proxy.$refs.gridFileTable as any;
  // 读取附件
  $grid
    .readFile({
      multiple: true,
      types: ['xlsx', 'txt', 'docx', 'doc', 'pdf', 'zip', 'rar']
    })
    .then((params) => {
      const { files } = params;
      // 解析数据并显示
      Array.from(files).forEach((file: any) => {
        uploadByUrl(file);
      });
    });
}
function uploadByUrl(file) {
  let url = '/api/wk/WkFile/uploadFiles';
  const fd = new FormData();
  fd.append('file', file);
  fd.append('folderId', currentFolder.id);

  proxy.$http
    .post(url, fd)
    .then((res: any) => {
      findFilesManagementList();
    })
    .catch((err) => {
      (this as any).$XModal.message({ content: err.data.error.message, status: 'warning' });
    });
}
function download() {
  if (isEmpty(currentFilesManagement)) {
    VxeMessage('选择要下载得文件', VxeNotifyType.error);
    return;
  }
  if (currentFilesManagement.fileExten == 'explorer') {
    VxeMessage('选择要下载得文件', VxeNotifyType.error);
    return;
  }

  const blob = new Blob([], { type: 'application/excel;charset=utf-8' });
  const downloadElement = document.createElement('a');
  const href = window.URL.createObjectURL(blob); //创建下载链接
  const fileUrl = (window as any).apiUrl.VITE_SERVER_URL + '/api/wk/WkFile/downWkFile';

  downloadElement.href = fileUrl + '?id=' + currentFilesManagement.id; // 此处可以通过拼接字符串的方式传递参数
  document.body.appendChild(downloadElement);
  downloadElement.click(); // 点击下载
  document.body.removeChild(downloadElement); // 下载完成之后移除元素
  window.URL.revokeObjectURL(href); // 释放掉blob对象
}

function handleDeleteFile() {
  if (isEmpty(currentFilesManagement)) {
    VxeMessage('选择要删除得文件', VxeNotifyType.error);
    return;
  }
  if (currentFilesManagement.fileExten == 'explorer') {
    proxy
      .$confirm('确定删除此文件夹？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        const url = '/api/wk/wkFolder/deleteFolder';
        proxy.$http.post(url, currentFilesManagement).then((res: any) => {
          if (res.status.code === 1) {
            findFolderList();
            VxeMessage('删除文件夹成功', VxeNotifyType.success);
          } else {
            VxeMessage(res.status.msg, VxeNotifyType.error);
          }
        });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  } else {
    proxy
      .$confirm('确定删除此文件？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        const url = '/api/wk/WkFile/deleteFile';
        proxy.$http.post(url, currentFilesManagement).then((res: any) => {
          if (res.status.code === 1) {
            findFilesManagementList();
            VxeMessage('删除文件成功', VxeNotifyType.success);
          } else {
            VxeMessage(res.status.msg, VxeNotifyType.error);
          }
        });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}
function filesManagementRowClick() {
  console.log('filesManagementRowClick');
}

function renameBlurEvent(item, index) {
  item.isRename = false;
  if (item.fileExten === 'explorer') {
    editFolderRow(item);
  } else {
    renameFile(item);
  }
}

function renameFile(row) {
  if (row.name === sltFileName) {
    return;
  }
  // 修改用户
  const url = '/api/wk/WkFile/editFile';
  const folder = {
    id: row.id,
    name: row.name
  };
  proxy.$http
    .post(url, folder)
    .then((res: any) => {
      VxeMessage('修改成功', VxeNotifyType.success);
      findFilesManagementList();
    })
    .catch((err: any) => {
      VxeMessage('修改失败', VxeNotifyType.error);
    });
}

// 选择点击地址栏某一项
function clickUrlPath(val) {
  const index = folderList.findIndex((row) => {
    return row.id === val.id;
  });
  if (index !== -1) {
    folderRowClick({ row: val });
  }
}

function copyFileButton() {
  if (isEmpty(currentFilesManagement)) {
    VxeMessage('请先选择要复制得文件', VxeNotifyType.error);
  } else {
    copyFile = JSON.parse(JSON.stringify(currentFilesManagement));
  }
  if (!isEmpty(copyFile)) {
    pasteTag.value = false;
  }
}

function renameButton() {
  if (previewType.value == 'list') {
    (proxy.$refs.filesManagementTable as any).setEditRow(currentFilesManagement);
    return;
  } else {
    if (currentFilesManagement.fileExten == 'explorer') {
      sltFolderName = currentFilesManagement.name;
    } else {
      sltFileName = currentFilesManagement.name;
    }
  }
  filesManagementList.forEach((e, i) => {
    if (e.isSelected) {
      e.isRename = true;
      proxy.$nextTick(() => {
        const a = 'rename' + i;
        const vxeInputs = proxy.$refs[a] as any;
        if (vxeInputs) {
          try {
            vxeInputs.forEach((e) => {
              e.focus();
            });
          } catch (error) {
            //todo
          }
        }
      });
    }
  });
}
</script>

<style lang="scss" scoped>
#filemanageDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      height: calc(100% - 30px);
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .sampleType {
        height: 100%;
        :deep(.el-scrollbar__view) {
          height: 100%;
        }
      }
    }

    .container {
      display: flex;
      flex-wrap: wrap;
      overflow-y: auto;
      align-content: flex-start;
      align-items: flex-start;
    }

    /* 使用伪元素辅助左对齐 */
    .container::after {
      content: '';
      flex: auto;
      /* 或者flex: 1 */
    }

    .list {
      height: auto;
      margin-top: 2px;
      cursor: pointer;
      padding: 5px;
    }

    .list.title {
      display: flex;
      justify-content: center;
      text-align: center;
      vertical-align: middle;
    }

    .list.selected {
      background-color: rgba(135, 206, 235, 0.45);
      border: 0px solid skyblue;
      border-radius: 5px;
      margin-top: 2px;
      cursor: pointer;
      padding: 5px;
    }

    .list:hover {
      background-color: rgba(135, 206, 235, 0.2);
      border: 0px solid skyblue;
      border-radius: 5px;
      margin-top: 2px;
      cursor: pointer;
      padding: 5px;
    }

    .bg-image-wh {
      width: 60px;
      height: 60px;
      background-repeat: no-repeat;
      background-size: contain;
    }
    .current-path-inner {
      width: 100%;
      height: 22px;
      border-radius: 0px;
      outline: 0;
      margin: 0;
      font-size: inherit;
      font-family: inherit;
      line-height: inherit;
      padding: 0 0.1em;
      color: #000;
      border: 1px solid #dcdfe6;
      background-color: #fff;
      -webkit-box-shadow: none;
      box-shadow: none;
    }

    .path-item {
      vertical-align: middle;
      font-size: 1em;
      font-style: normal;
      font-weight: 500;
      margin-left: 5px;
    }

    .path-item:hover {
      background-color: rgba($color: #ff9900, $alpha: 0.2);
    }
  }
}
</style>